<!--

    Copyright © 2016-2024 The Thingsboard Authors

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<div class="connector-container tb-form-panel no-border">
  <section class="table-section tb-form-panel no-padding flex section-container">
    <mat-toolbar class="mat-mdc-table-toolbar">
      <h2>{{ 'gateway.connectors' | translate }}</h2>
      <span fxFlex></span>
      <button *ngIf="dataSource?.data?.length"
              mat-icon-button
              [disabled]="isLoading$ | async"
              (click)="addConnector($event)"
              matTooltip="{{ 'action.add' | translate }}"
              matTooltipPosition="above">
        <mat-icon>add</mat-icon>
      </button>
    </mat-toolbar>
    <div class="table-container">
      <section *ngIf="!dataSource?.data?.length" fxLayoutAlign="center center"
               class="mat-headline-5 tb-absolute-fill tb-add-new">
        <button mat-button class="connector"
        (click)="addConnector($event)">
          <mat-icon class="tb-mat-96">add</mat-icon>
          <span>{{ 'gateway.add-connector' | translate }}</span>
        </button>
      </section>
      <table mat-table [dataSource]="dataSource"
             matSort [matSortActive]="pageLink.sortOrder.property" [matSortDirection]="pageLink.sortDirection()"
             matSortDisableClear>
        <ng-container matColumnDef="enabled" sticky>
          <mat-header-cell *matHeaderCellDef style="width: 60px;min-width: 60px;">
            {{ 'gateway.connectors-table-enabled' | translate }}
          </mat-header-cell>
          <mat-cell *matCellDef="let attribute">
            <mat-slide-toggle [checked]="activeConnectors.includes(attribute.key)"
                              (click)="$event.stopPropagation(); onEnableConnector(attribute)"></mat-slide-toggle>
          </mat-cell>
        </ng-container>
        <ng-container matColumnDef="key">
          <mat-header-cell *matHeaderCellDef mat-sort-header style="width: 40%">
            {{ 'gateway.connectors-table-name' | translate }}</mat-header-cell>
          <mat-cell *matCellDef="let attribute">
            {{ attribute.key }}
          </mat-cell>
        </ng-container>
        <ng-container matColumnDef="type">
          <mat-header-cell *matHeaderCellDef mat-sort-header style="width: 30%">
            {{ 'gateway.connectors-table-type' | translate }}
          </mat-header-cell>
          <mat-cell *matCellDef="let attribute" style="text-transform: uppercase">
            {{ returnType(attribute) }}
          </mat-cell>
        </ng-container>
        <ng-container matColumnDef="syncStatus">
          <mat-header-cell *matHeaderCellDef mat-sort-header style="width: 30%">
            {{ 'gateway.configuration' | translate }}
          </mat-header-cell>
          <mat-cell *matCellDef="let attribute" style="text-transform: uppercase">
              <div class="status" [class]="isConnectorSynced(attribute) ? 'status-sync' : 'status-unsync'">
                {{ isConnectorSynced(attribute) ? 'sync' : 'out of sync' }}
              </div>
          </mat-cell>
        </ng-container>
        <ng-container matColumnDef="errors">
          <mat-header-cell *matHeaderCellDef mat-sort-header style="width: 30%">
            {{ 'gateway.connectors-table-status' | translate }}
          </mat-header-cell>
          <mat-cell *matCellDef="let attribute" style="text-transform: uppercase">
            <span class="dot"
                  matTooltip="{{ 'Errors: '+ getErrorsCount(attribute)}}"
                  matTooltipPosition="above"
                  (click)="connectorLogs(attribute, $event)"
                  [class]="{'hasErrors': +getErrorsCount(attribute) > 0,
                            'noErrors': +getErrorsCount(attribute) === 0 || getErrorsCount(attribute) === ''}"></span>
          </mat-cell>
        </ng-container>
        <ng-container matColumnDef="actions" stickyEnd>
          <mat-header-cell *matHeaderCellDef
                           [ngStyle.gt-md]="{ minWidth: '144px', maxWidth: '144px', width: '144px', textAlign: 'center'}">
            {{ 'gateway.connectors-table-actions' | translate }}
          </mat-header-cell>
          <mat-cell *matCellDef="let attribute"
                    [ngStyle.gt-md]="{ minWidth: '144px', maxWidth: '144px', width: '144px'}">
            <div fxHide fxShow.gt-md fxFlex fxLayout="row" fxLayoutAlign="end">
              <button mat-icon-button
                      matTooltip="RPC"
                      matTooltipPosition="above"
                      (click)="connectorRpc(attribute, $event)">
                <mat-icon>private_connectivity</mat-icon>
              </button>
              <button mat-icon-button
                      matTooltip="Logs"
                      matTooltipPosition="above"
                      (click)="connectorLogs(attribute, $event)">
                <mat-icon>list</mat-icon>
              </button>
              <button mat-icon-button
                      matTooltip="Delete connector"
                      matTooltipPosition="above"
                      (click)="deleteConnector(attribute, $event)">
                <mat-icon>delete</mat-icon>
              </button>
            </div>
            <div fxHide fxShow.lt-lg>
              <button mat-icon-button
                      (click)="$event.stopPropagation()"
                      [matMenuTriggerFor]="cellActionsMenu">
                <mat-icon class="material-icons">more_vert</mat-icon>
              </button>
              <mat-menu #cellActionsMenu="matMenu" xPosition="before">
                <button mat-icon-button
                        matTooltip="RPC"
                        matTooltipPosition="above"
                        (click)="connectorRpc(attribute, $event)">
                  <mat-icon>private_connectivity</mat-icon>
                </button>
                <button mat-icon-button
                        matTooltip="Logs"
                        matTooltipPosition="above"
                        (click)="connectorLogs(attribute, $event)">
                  <mat-icon>list</mat-icon>
                </button>
                <button mat-icon-button
                        matTooltip="Delete connector"
                        matTooltipPosition="above"
                        (click)="deleteConnector(attribute, $event)">
                  <mat-icon>delete</mat-icon>
                </button>
              </mat-menu>
            </div>
          </mat-cell>
        </ng-container>
        <mat-header-row class="mat-row-select"
                        *matHeaderRowDef="displayedColumns; sticky: true"></mat-header-row>
        <mat-row class="mat-row-select" [class]="{'tb-current-entity': isSameConnector(attribute)}"
                 *matRowDef="let attribute; let i = index; columns: displayedColumns;" (click)="selectConnector($event, attribute)"></mat-row>
      </table>
    </div>
  </section>
  <section [formGroup]="connectorForm" class="tb-form-panel section-container flex">
    <div class="tb-form-panel-title tb-flex no-flex space-between align-center">
      <div class="tb-form-panel-title">
        {{ initialConnector?.type ? GatewayConnectorTypesTranslatesMap.get(initialConnector.type) : '' }}
        {{ 'gateway.configuration' | translate }}
        <span class="version-placeholder" *ngIf="connectorForm.get('configVersion').value">v{{connectorForm.get('configVersion').value}}</span>
      </div>
      <tb-toggle-select *ngIf="initialConnector && allowBasicConfig.has(initialConnector.type)"
                        formControlName="mode" appearance="fill">
        <tb-toggle-option [value]="ConnectorConfigurationModes.BASIC">
          {{ 'gateway.basic' | translate }}
        </tb-toggle-option>
        <tb-toggle-option [value]="ConnectorConfigurationModes.ADVANCED">
          {{ 'gateway.advanced' | translate }}
        </tb-toggle-option>
      </tb-toggle-select>
    </div>
    <span [fxShow]="!initialConnector"
          fxLayoutAlign="center center"
          class="no-data-found" translate>
      gateway.select-connector
    </span>
    <section class="tb-form-panel section-container no-border no-padding tb-flex space-between" *ngIf="initialConnector">
      <ng-container *ngIf="connectorForm.get('mode')?.value === ConnectorConfigurationModes.BASIC else defaultConfig">
        <ng-container [ngSwitch]="initialConnector.type">
          <ng-container *ngSwitchCase="ConnectorType.MQTT">
            <tb-mqtt-basic-config
              *ngIf="connectorForm.get('configVersion').value === GatewayVersion.Current else legacy"
              formControlName="basicConfig"
              [generalTabContent]="generalTabContent"
            />
            <ng-template #legacy>
              <tb-mqtt-legacy-basic-config formControlName="basicConfig" [generalTabContent]="generalTabContent"/>
            </ng-template>
          </ng-container>
          <ng-container *ngSwitchCase="ConnectorType.OPCUA">
            <tb-opc-ua-basic-config
              *ngIf="connectorForm.get('configVersion').value === GatewayVersion.Current else legacy"
              formControlName="basicConfig"
              [generalTabContent]="generalTabContent"
            />
            <ng-template #legacy>
              <tb-opc-ua-legacy-basic-config formControlName="basicConfig" [generalTabContent]="generalTabContent"/>
            </ng-template>
          </ng-container>
          <ng-container *ngSwitchCase="ConnectorType.MODBUS">
            <tb-modbus-basic-config
              *ngIf="connectorForm.get('configVersion').value === GatewayVersion.Current else legacy"
              formControlName="basicConfig"
              [generalTabContent]="generalTabContent"
            />
            <ng-template #legacy>
              <tb-modbus-legacy-basic-config formControlName="basicConfig" [generalTabContent]="generalTabContent"/>
            </ng-template>
          </ng-container>
        </ng-container>
      </ng-container>
      <ng-template #defaultConfig>
        <mat-tab-group>
          <mat-tab label="{{ 'gateway.general' | translate }}">
            <ng-container [ngTemplateOutlet]="generalTabContent"></ng-container>
          </mat-tab>
          <mat-tab label="{{ 'gateway.configuration' | translate }}*">
            <tb-json-object-edit
              fillHeight="true"
              class="tb-flex fill-height"
              fxLayout="column"
              jsonRequired
              label="{{ 'gateway.configuration' | translate }}"
              formControlName="configurationJson">
            </tb-json-object-edit>
          </mat-tab>
        </mat-tab-group>
      </ng-template>
      <div fxLayoutAlign="end center">
        <button mat-raised-button color="primary"
                type="button"
                [disabled]="!connectorForm.dirty || connectorForm.invalid"
                (click)="saveConnector()">
          {{ 'action.save' | translate }}
        </button>
      </div>
    </section>
  </section>
</div>
<ng-template #generalTabContent>
  <section [formGroup]="connectorForm" class="tb-form-panel no-border no-padding padding-top section-container flex">
    <div class="tb-form-row column-xs" fxLayoutAlign="space-between center" >
      <div class="fixed-title-width tb-required" translate>gateway.name</div>
      <div class="tb-flex no-gap">
        <mat-form-field class="tb-flex no-gap" appearance="outline" subscriptSizing="dynamic">
          <input matInput autocomplete="off" name="value" formControlName="name" placeholder="{{ 'gateway.set' | translate }}"/>
          <mat-icon matSuffix
                    matTooltipPosition="above"
                    matTooltipClass="tb-error-tooltip"
                    [matTooltip]="(connectorForm.get('name').hasError('duplicateName') ?
                                    'gateway.connector-duplicate-name' : 'gateway.name-required') | translate"
                    *ngIf="(connectorForm.get('name').hasError('required') && connectorForm.get('name').touched) ||
                                    connectorForm.get('name').hasError('duplicateName')"
                    class="tb-error">
            warning
          </mat-icon>
        </mat-form-field>
      </div>
    </div>
    <div *ngIf="connectorForm.get('type').value === ConnectorType.CUSTOM" class="tb-form-row column-xs" fxLayoutAlign="space-between center">
      <div class="fixed-title-width" translate>gateway.connectors-table-class</div>
      <div class="tb-flex no-gap">
        <mat-form-field class="tb-flex no-gap" appearance="outline" subscriptSizing="dynamic">
          <input matInput name="value" formControlName="class" placeholder="{{ 'gateway.set' | translate }}"/>
        </mat-form-field>
      </div>
    </div>
    <div *ngIf="connectorForm.get('type').value === ConnectorType.GRPC" class="tb-form-row column-xs" fxLayoutAlign="space-between center">
      <div class="fixed-title-width" translate>gateway.connectors-table-key</div>
      <div class="tb-flex no-gap">
        <mat-form-field class="tb-flex no-gap" appearance="outline" subscriptSizing="dynamic">
          <input matInput name="value" formControlName="key" placeholder="{{ 'gateway.set' | translate }}"/>
        </mat-form-field>
      </div>
    </div>
    <div class="tb-form-panel stroked">
      <div class="tb-form-panel-title" translate>gateway.logs-configuration</div>
      <div class="tb-form-row" fxLayoutAlign="space-between center">
        <mat-slide-toggle class="mat-slide" formControlName="enableRemoteLogging">
          <mat-label>
            {{ 'gateway.enable-remote-logging' | translate }}
          </mat-label>
        </mat-slide-toggle>
      </div>
      <div class="tb-form-row column-xs" fxLayoutAlign="space-between center">
        <div class="fixed-title-width" translate>gateway.remote-logging-level</div>
        <div class="tb-flex no-gap">
          <mat-form-field class="tb-flex no-gap" appearance="outline" subscriptSizing="dynamic">
            <mat-select formControlName="logLevel">
              <mat-option *ngFor="let logLevel of gatewayLogLevel" [value]="logLevel">{{ logLevel }}</mat-option>
            </mat-select>
          </mat-form-field>
        </div>
      </div>
    </div>
    <div *ngIf="connectorForm.get('type').value === ConnectorType.MQTT" class="tb-form-row column-xs" fxLayoutAlign="space-between center">
      <mat-slide-toggle class="mat-slide" formControlName="sendDataOnlyOnChange">
        <mat-label tb-hint-tooltip-icon="{{ 'gateway.send-change-data-hint' | translate }}">
          {{ 'gateway.send-change-data' | translate }}
        </mat-label>
      </mat-slide-toggle>
    </div>
  </section>
</ng-template>
